import {Injectable, InjectionToken} from '@angular/core';
import {Observable, of} from "rxjs";
import { comments } from '../data/coommon/comments';

@Injectable({
  providedIn: 'root',
})
export class CommentService {
  constructor() {
  }

  getComments2(): Observable<CommentType[]> {
    return of(comments);
  }

  getComment(id: number): CommentType | undefined {
    for (let comment of comments) {
      if (comment.id == id) {
        return comment;
      }
    }
    return undefined;
  }

  getComment2(id: number): CommentType | undefined {
    return comments.find(comment => comment.id == id)
  }

  getComments(): CommentType[] {
    return comments;
  }

  getFirstComment(): CommentType {
    return this.getComments()[0]
  }

  getCommentsByIndex(index = 0): CommentType[] {
    let comments: CommentType[] = this.getComments();
    if (index > comments.length || index < 0) {
      return comments;
    } else {
      return comments.slice(index, index + 1);
    }
  }
}

// http://jsonplaceholder.typicode.com/comments
// 定义接口
export interface CommentType {
  postId: number;
  id: number;
  name: string;
  email: string;
  body: string;
}

// 导出 括号里面的参数是该令牌的一个描述，可选
export const CommentTyeInjectionToken = new InjectionToken<Comment>('comment type');
